<?php

namespace app\test\controller;

use app\common\cachemodel\ZlSynastryReport;
use app\common\cachemodel\ZlUserVip;
use app\common\lib\AMQP;
use app\common\lib\astrolog\Astrolog;
use app\common\lib\astrolog\AuthenticateLove;
use app\common\lib\astrolog\FortunesChange;
use app\common\lib\astrolog\Synastry;
use app\common\lib\astrolog\SynastryReport;
use app\common\lib\horoscope\Horoscope;
use app\common\lib\Kafka;
use app\common\lib\Util;
use app\common\model\Recode;
use app\common\model\User;
use think\Cache;
use think\Controller;
use think\Db;

//use think\cache\driver\Redis;
//use app\base\controller\RedisHash;
class Index extends Controller
{
    public function getBaziForAi()
    {
        echo '<pre>';

//        $rid = input('rid/d', 0); // 4923624
//        $uid = input('uid/d', 0);
//        $time = input('year/s', date('Y-m-d'));
//        if ($rid > 0)
//        {
//            $map = [
//                'id' => $rid,
//            ];
//        } elseif ($uid > 0)
//        {
//            $map = [
//                'uid' => $uid,
//                'isself' => 1,
//            ];
//        } else
//        {
//            $map = [
//                'uid' => 12345805,
//                'isself' => 1,
//                'status' => 1,
//            ];
//        }
//        $timestamp = strtotime($time);
//        $recode = Db::table('wechat_backup_07_18_14_43_00.app_recode')->where($map)->field('id,uid,aid,isself,name,type,year,month,day,hour,minute,timezone,birth_country,birth_province,birth_city,live_country,live_province,live_city,comments,long_deg,long_min,ew,lat_deg,lat_min,ns,is_summer')->find();
//        $data = Horoscope::getInstance([
//            'recode' => $recode,
//            'time_start' => 23,
//            'time_type' => 0,
//        ])->getUserDataForAI();

//        print_r($data);

        $map = [
            'id' => ['in', [4921746, 4921747, 4921748, 4921749]]
        ];
        $recode = Db::table('wechat_backup_07_18_14_43_00.app_recode')->where($map)->field('id,uid,aid,isself,name,type,year,month,day,hour,minute,timezone,birth_country,birth_province,birth_city,live_country,live_province,live_city,comments,long_deg,long_min,ew,lat_deg,lat_min,ns,is_summer')->select();
        $data =  Horoscope::getInstance([
            'recode' => $recode[0],
            'time_start' => 23,
            'time_type' => 0,
        ])->getUserDataForQiming($recode);

        print_r($data);

    }

    private function astroCard()
    {
        $record1 = [
            'id' => 4922357,
            'name' => '测试合盘报告1',
            'type' => 2,
            'year' => 1989,
            'month' => 2,
            'day' => 17,
            'hour' => 21,
            'minute' => 15,
            'timezone' => 8,
            'birth_country' => '重庆市',
            'birth_province' => '重庆市',
            'birth_city' => '大足县',
            'live_country' => '北京市',
            'live_province' => '北京市',
            'live_city' => '朝阳区',
            'comments' => '案例',
            'isself' => 0,
            'long_deg' => 105,
            'long_min' => 46,
            'ew' => 1,
            'lat_deg' => 29,
            'lat_min' => 29,
            'ns' => 1,
            'avatar' => '',
            'is_summer' => 0,
        ];
        $res1 = (new \app\web\service\AstroCard())->getElementData($record1);
        $res2 = (new \app\web\service\AstroCard())->getInstructionData($record1);

        echo '<pre>';
        print_r($res1);
        print_r($res2);
    }

    public function ziwei()
    {
        (new \app\common\lib\ziwei\Ziwei())->setRecordInfo()->getChartInfo();
    }

    private function testSynastry2024()
    {
        $record1 = [
            'id' => 4922357,
            'name' => '测试合盘报告1',
            'type' => 2,
            'year' => 1989,
            'month' => 2,
            'day' => 17,
            'hour' => 21,
            'minute' => 15,
            'timezone' => 8,
            'birth_country' => '重庆市',
            'birth_province' => '重庆市',
            'birth_city' => '大足县',
            'live_country' => '北京市',
            'live_province' => '北京市',
            'live_city' => '朝阳区',
            'comments' => '案例',
            'isself' => 0,
            'long_deg' => 105,
            'long_min' => 46,
            'ew' => 1,
            'lat_deg' => 29,
            'lat_min' => 29,
            'ns' => 1,
            'avatar' => '',
            'is_summer' => 0,
        ];
        $record2 = [
            'id' => 4922358,
            'name' => '测试合盘报告2',
            'type' => 1,
            'year' => 1989,
            'month' => 12,
            'day' => 7,
            'hour' => 10,
            'minute' => 30,
            'timezone' => 8,
            'birth_country' => '湖北省',
            'birth_province' => '黄冈市',
            'birth_city' => '市辖区',
            'live_country' => '北京市',
            'live_province' => '北京市',
            'live_city' => '朝阳区',
            'comments' => '案例',
            'isself' => 0,
            'long_deg' => 114,
            'long_min' => 52,
            'ew' => 1,
            'lat_deg' => 30,
            'lat_min' => 26,
            'ns' => 1,
            'avatar' => '',
            'is_summer' => 0,
        ];

//        $record2 = json_decode('{"id":"4924032","uid":"12346776","name":"\u81ea\u5df1","type":"2","year":"1997","month":"1","day":"1","hour":"12","minute":"0","timezone":"8","long_deg":"116","long_min":"25","ew":"1","lat_deg":"39","lat_min":"56","ns":"1","avatar":"","is_summer":"0","isself":"1","sun":"10-10-280.7774808","moon":"7-6-180.7353027","asc":"1-1-12.3585286","name_old":"\u98ce\u98ce\u5149\u5149"}', true);
//        $record1 = json_decode('{"id":"4924332","uid":"12346776","name":"\u54af\u58a8\u8ff9","type":"2","year":"2000","month":"1","day":"1","hour":"12","minute":"0","timezone":"8","long_deg":"116","long_min":"25","ew":"1","lat_deg":"39","lat_min":"56","ns":"1","avatar":"","is_summer":"0","isself":"0"}', true);

//        $record1 = json_decode('{ "id": 4923678, "name": "不过现在", "type": 2, "year": 1989, "month": 5, "day": 7, "hour": 12, "minute": 0, "timezone": 8, "birth_country": "北京市", "birth_province": "北京市", "birth_city": "东城区", "live_country": "北京市", "live_province": "北京市", "live_city": "东城区", "comments": "朋友", "isself": 0, "long_deg": 116, "long_min": 25, "ew": 1, "lat_deg": 39, "lat_min": 56, "ns": 1, "avatar": "", "is_summer": 1, "uid": 12346294, "aid": 4923992, "sun": "2-10-46.5377207", "moon": "3-11-69.1108612", "merc": "3-11-65.6308906", "venu": "2-10-54.8978336", "mars": "4-11-94.9060016", "jupi": "3-11-70.8994422", "satu": "10-6-283.7655159", "non": "12-8-331.1094132", "lili": "7-3-189.7293634", "juno": "5-1-147.5766937", "asc": "5-1-129.5638372", "mc": "1-10-28.3695465", "is_read": 1, "channel_des": null }',true);
//        $record2 = json_decode('{ "id": 4923200, "name": "小苹果", "type": 2, "year": 2002, "month": 10, "day": 1, "hour": 17, "minute": 7, "timezone": 8, "birth_country": "北京市", "birth_province": "北京市", "birth_city": "东城区", "live_country": "北京市", "live_province": "北京市", "live_city": "东城区", "comments": "自己", "isself": 1, "long_deg": 116, "long_min": 25, "ew": 1, "lat_deg": 39, "lat_min": 56, "ns": 1, "avatar": "\/uploads\/20240428\/3b4c3b65c5eda8096077c6fe2f2b9ba6.png", "is_summer": 0, "uid": 12346294, "aid": 4923510, "sun": "7-7-188.0176914", "moon": "4-5-118.3831981", "merc": "7-7-180.8090221", "venu": "8-8-223.996036", "mars": "6-7-170.85135", "jupi": "5-6-132.1857135", "satu": "3-4-88.9897573", "non": "3-3-71.8806684", "lili": "1-1-15.2906919", "juno": "7-7-189.5600582", "asc": "12-1-348.2459826", "mc": "9-10-263.659584", "is_read": 1, "channel_des": null }',true);

//            'id' => 4921747,// 奇
//            'id' => 4921761,// 鼎
//            'id' => 4921746,// 黑
//            'id' => 4923211,// 皓元
        $recodeModel = new Recode();
        $record1 = $recodeModel->where(['id' => 33156329])->find();
        $record2 = $recodeModel->where(['id' => 33156330])->find();


        $data = (new Synastry())->getData2024($record1, $record2, 8);

        echo '<pre>';
        print_r($data);
    }

    private function dingding()
    {
        $time = time() * 1000;
        $sec = 'SECcd9cc7f9e863073d9ebd0a2d0c9ed2f38d38ffcd67b700866d97ab3f919eb419';
        $sign = urldecode(base64_encode(hash_hmac('sha256', $time . "\n" . $sec, $sec, true)));
        $url = "https://oapi.dingtalk.com/robot/send?access_token=b93977081e77642ab22db0e369abc12e08389a99441b3cc2ed6b3f675d8e9d7e&timestamp={$time}&sign={$sign}";

        $str = '{
            "msgtype": "text",
            "text": {
                "content": "1只是在测试at  \n  这是第二行  \n  这是第三行  \n  这是第四行"
            },
            "at": {
                "atMobiles": [
                    "18511696867",
                    "17800241292"
                ]
            }
        }';
//        $str = '{
//             "msgtype": "markdown",
//             "markdown": {
//                 "title":"杭州天气",
//                 "text": "#### 杭州天气 @150XXXXXXXX \n > 9度，西北风1级，空气良89，相对温度73%\n > ![screenshot](https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png)\n > ###### 10点20分发布 [天气](https://www.dingtalk.com) \n"
//             },
//              "at": {
//                  "atMobiles": [
//                      "18511696867"
//                  ],
//                  "isAtAll": false
//              }
//         }';
        $str = json_decode($str, true);
        $str = json_encode($str, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

        $a = Util::curlRequest('POST', $url, $str, ['Content-Type: application/json;charset=utf-8']);

        var_dump($a);
    }

    private function testSynastryReport()
    {
        $param = $this->request->param();
        $relation = input('relation/d', 1);//1单恋、2已恋、3分手、4已婚
        if (isset($param['id']))
        {
            $res = (new ZlSynastryReport())->getInfoById($param['id'], ['recode_info', 'start_time', 'relation_id']);
            $recode = json_decode($res['recode_info'], true);
            $record1 = $recode['recode1'];
            $record2 = $recode['recode2'];
            $startTime = $res['start_time'];
            $relation = $res['relation_id'];
        } elseif (isset($param['rid1']))
        {
            $recodeModel = new Recode();
            $record1 = $recodeModel->where(['id' => $param['rid1']])->find();
            $record2 = $recodeModel->where(['id' => $param['rid2']])->find();
            $startTime = $param['start_time'];// 下单时间，具体推运时间开始时间需要使用下面返回的start_time
        } else
        {
            $record1 = [
                'id' => 4922357,
                'name' => '测试合盘报告1',
                'type' => 2,
                'year' => 1989,
                'month' => 2,
                'day' => 17,
                'hour' => 21,
                'minute' => 15,
                'timezone' => 8,
                'birth_country' => '重庆市',
                'birth_province' => '重庆市',
                'birth_city' => '大足县',
                'live_country' => '北京市',
                'live_province' => '北京市',
                'live_city' => '朝阳区',
                'comments' => '案例',
                'isself' => 0,
                'long_deg' => 105,
                'long_min' => 46,
                'ew' => 1,
                'lat_deg' => 29,
                'lat_min' => 29,
                'ns' => 1,
                'avatar' => '',
                'is_summer' => 0,
            ];
            $record2 = [
                'id' => 4922358,
                'name' => '测试合盘报告2',
                'type' => 1,
                'year' => 1989,
                'month' => 12,
                'day' => 7,
                'hour' => 10,
                'minute' => 30,
                'timezone' => 8,
                'birth_country' => '湖北省',
                'birth_province' => '黄冈市',
                'birth_city' => '市辖区',
                'live_country' => '北京市',
                'live_province' => '北京市',
                'live_city' => '朝阳区',
                'comments' => '案例',
                'isself' => 0,
                'long_deg' => 114,
                'long_min' => 52,
                'ew' => 1,
                'lat_deg' => 30,
                'lat_min' => 26,
                'ns' => 1,
                'avatar' => '',
                'is_summer' => 0,
            ];
            $startTime = strtotime('2017-06-01 00:00:00');// 下单时间，具体推运时间开始时间需要使用下面返回的start_time
        }
        //案例：
        //19890217 21 点 15 重庆大足县
        //19891207 10 点 30 湖北黄冈市辖区
        //推运起始年月：2017 年 6 月

        $data = (new SynastryReport())->setRecode1($record1)
            ->setRecode2($record2)
            ->setRelation($relation)//1单恋、2已恋、3分手、4已婚
            ->setStartTime($startTime)
            ->getReportData();

        echo "<pre>";
        print_r($data);

    }

    /**
     * 用户绑定手机号任务，增加星力值
     */
    private function testStar()
    {
        (new ZlUserVip())->updateStarNum(14593357, 13); // 绑定手机号任务
        echo "线上uid:14593357增加星力值成功";
        exit;
    }

    private $dayCyclical = [
        0 => ['month' => 3, 'min' => 20, 'max' => 21],// 春分
        15 => ['month' => 4, 'min' => 4, 'max' => 6],// 清明
        30 => ['month' => 4, 'min' => 19, 'max' => 21],// 谷雨
        45 => ['month' => 5, 'min' => 5, 'max' => 7],// 立夏
        60 => ['month' => 5, 'min' => 20, 'max' => 22],// 小满
        75 => ['month' => 6, 'min' => 5, 'max' => 7],// 芒种
        90 => ['month' => 6, 'min' => 21, 'max' => 22],// 夏至
        105 => ['month' => 7, 'min' => 6, 'max' => 8],// 小暑
        120 => ['month' => 7, 'min' => 22, 'max' => 24],// 大暑
        135 => ['month' => 8, 'min' => 7, 'max' => 9],// 立秋
        150 => ['month' => 8, 'min' => 22, 'max' => 24],// 处暑
        165 => ['month' => 9, 'min' => 7, 'max' => 7],// 白露
        180 => ['month' => 9, 'min' => 22, 'max' => 24],// 秋分
        195 => ['month' => 10, 'min' => 8, 'max' => 9],// 寒露
        210 => ['month' => 10, 'min' => 23, 'max' => 24],// 霜降
        225 => ['month' => 11, 'min' => 7, 'max' => 8],// 立冬
        240 => ['month' => 11, 'min' => 22, 'max' => 23],// 小雪
        255 => ['month' => 12, 'min' => 6, 'max' => 8],// 大雪
        270 => ['month' => 12, 'min' => 21, 'max' => 23],// 冬至
        285 => ['month' => 1, 'min' => 5, 'max' => 7],// 小寒
        300 => ['month' => 1, 'min' => 20, 'max' => 21],// 大寒
        315 => ['month' => 2, 'min' => 3, 'max' => 5],// 立春
        330 => ['month' => 2, 'min' => 18, 'max' => 20],// 雨水
        345 => ['month' => 3, 'min' => 5, 'max' => 7],// 惊蛰
    ];

    // 用于模拟登录
    private function Login()
    {
        $accessToken = input('access-token') . '||' . input('uid');
        $b = base64_encode(openssl_encrypt($accessToken, 'AES-128-CBC', 'aiVjKg65lvKaYBuN', OPENSSL_RAW_DATA, 'EPzH5lnC5a47QEYo'));

//        $a = 'omvrOWbAXhW7GGcHwzFgSGyHO9+/vQw25J5SWyv6OC3B49zi26n+t32qO/lgfXY7qHtw2SoVGPvpvAZBvSdvEA==';

//        $b = openssl_decrypt(base64_decode($a),'AES-128-CBC','aiVjKg65lvKaYBuN',OPENSSL_RAW_DATA,'EPzH5lnC5a47QEYo');

        echo
        $b;

        exit;
    }

    /**
     * @return array
     * @throws \app\common\lib\exception\ApiException
     */
    private function index()
    {
//        return $this->redirect('https://itunes.apple.com/cn/app/wei/id1356471277');
        $FortunesForYear = new FortunesChange();

        $type = 'month';

        // 使用系统默认配置
        $setting['use_default_setting'] = true;
        $setting['get_now_data'] = true;
        $setting['get_natal_data'] = true;
        $setting['get_transits_data'] = true;
        $setting['get_thirdprogressed_data'] = true;

        $Astrolog = Astrolog::getInstance();

        $recode = (new Recode())->getRecode(['id' => 333]);

        $recode['longitude'] = ($recode['long_deg'] + $recode['long_min'] / 60) * $recode['ew'];
        $recode['latitude'] = ($recode['lat_deg'] + $recode['lat_min'] / 60) * $recode['ns'];

        $Astrolog->options['recode1'] = $recode;

        // 运势起始日期
        $timestamp = strtotime('2018-12-01 12:00');

        $today = strtotime(date('Y-m-d', time()));// 今天的日期  年-月-日

        $result = $topics = $scores = $temp = [];

        for ($i = $timestamp; $i < strtotime('+1 month', $timestamp); $i = strtotime('+1 day', $i))
        {
            $date = date('Y-m-d H:i', $i);
            // 推进时间
            $Astrolog->options['advance'] = [
                'year' => (int)(date('Y', $i)),
                'month' => (int)(date('m', $i)),
                'day' => (int)(date('d', $i)),
                'hour' => (int)(date('H', $i)),
                'minute' => (int)(date('i', $i)),
                'timezone' => 8,
                'is_summer' => 0,
                'longitude' => $recode['longitude'],// 使用本命经纬度
                'latitude' => $recode['latitude'],// 使用本命经纬度
            ];

//            $Astrolog->options['get_now_data'] = true;// 获取天象盘数据
            $Astrolog->options['get_natal_data'] = true;// 获取本命盘数据
            $Astrolog->options['get_transits_data'] = true;// 获取行运盘数据
            $Astrolog->options['get_thirdprogressed_data'] = true;// 获取三限盘数据

            $Astrolog->getAstroDatas();

            $source = $Astrolog->datas;

            $source['sex'] = $Astrolog->options['recode1']['type'];

            $FortunesForYear->options = ['date' => $date];

            $day = date('Y-m-d', $i);

            $topics[$day] = $FortunesForYear->getTopics($source);
            $scores[$day] = $FortunesForYear->getThirdprogressedScoreByDay($source);
        }

        /**
         * $day string 日期  年-月-日
         * $topic array 具体主题
         */
        foreach ($topics as $day => $topic)
        {
            foreach ($topic as $t)
            {
                $temp[$t['flag']][] = ['day' => $day, 'level' => $t['level']];
            }
        }
        $fortune_texts = config('fortune_text.common');

        $list = [];
        foreach ($temp as $k => $tmp)
        {
            $i = null;
            $j = -1;
            foreach ($tmp as $index => $d)
            {

                $level = $d['level'];
                unset($d['level']);
                /**
                 * 2018.12.01 这种格式的strtotime 无法转化  返回false
                 * 2018-12-01 可以正常转化
                 */
                $date_timestamp = strtotime($d['day'] . ' 00:00:00');
                /**
                 * 若 i 为 null 表示此运势为一段新的运势
                 */
                if ($i === null || $date_timestamp - $i > 86400)
                {
                    $j++;
                    $d['start_time'] = $date_timestamp;
                    $d['end_time'] = $date_timestamp;
                    unset($d['day']);
                    $list[$k][$j] = $d;
                    $list[$k][$j]['level'][] = $level;

                } /**
                 * 若 i 不为null 则表示此 可能为连续运势 需要进行比对
                 */
                elseif ($i !== null)
                {
                    if (strtotime($d['day']) - $i <= 86400)
                    {
                        $list[$k][$j]['end_time'] = $date_timestamp;
                        $list[$k][$j]['level'][] = $level;
                    }
                }

                $i = $date_timestamp;
            }
        }
        unset($d);
        foreach ($list as $key => $l)
        {
            $imp = explode('-', $key);
            $fortune_text = $fortune_texts[(int)($imp[0])];
            $num = (int)($imp[1]);
            foreach ($l as $d)
            {
                $d['icon'] = $fortune_text['icon'];
                $d['title'] = $fortune_text[$num]['title'];
                $d['status'] = $fortune_text[$num]['status'];
                $d['text'] = $fortune_text[$num]['text'];

                if (strtolower($type) === 'month')
                {
                    $d['suggestion_text'] = $fortune_text[$num]['suggestion_text'];
                    $all_days = ($d['end_time'] - $d['start_time']) / 86400 + 1;
                    $d['all_days'] = $all_days;
                }

                //
                /**
                 * 未来的运势
                 * level 显示第一天的级别
                 */
                if ($today < $d['start_time'])
                {
                    //predicted_fortune
                    $d['level'] = $d['level'][0];
                    $d['start_days'] = 0;
                    $d['end_days'] = ($d['end_time'] - $d['start_time']) / 86400 + 1;
                    $d['start_time'] = date('Y.m.d', $d['start_time']);
                    $d['end_time'] = date('Y.m.d', $d['end_time']);
                    $result['predicted_fortune'][] = $d;
                } /**
                 * 进行中的运势
                 * level 显示当天的级别
                 */
                elseif ($today >= $d['start_time'] && $today <= $d['end_time'])
                {
                    //underway_fortune
                    $index = ($today - $d['start_time']) / 86400;
                    $d['level'] = $d['level'][$index];
                    $d['start_days'] = $index + 1;
                    $d['end_days'] = ($d['end_time'] - $today) / 86400;
                    $d['start_time'] = date('Y.m.d', $d['start_time']);
                    $d['end_time'] = date('Y.m.d', $d['end_time']);
                    $result['underway_fortune'][] = $d;
                } /**
                 * 已完成的运势
                 * level 显示这段运势中最高的级别
                 */
                elseif ($today > $d['end_time'])
                {
                    //completed_fortune
                    $d['level'] = max($d['level']);
                    $d['start_days'] = ($d['end_time'] - $d['start_time']) / 86400 + 1;
                    $d['end_days'] = 0;
                    $d['start_time'] = date('Y.m.d', $d['start_time']);
                    $d['end_time'] = date('Y.m.d', $d['end_time']);
                    $result['completed_fortune'][] = $d;
                }
            }
        }

        return show(config('code.success'), '加载成功', $result);
    }

    private function solar_terms()
    {
        $data = \think\Db::table('app_solar_terms')->field('time,deg')->select();
//        var_dump($data);
        return var_export($data, true);
    }

    private function test()
    {
        // 当天 0点
        $start = gregoriantojd(3, 1, 1993) - 0.5;
        @putenv("PATH=:astrolog");
//        exec ("astrolog -edirastrolog -bj$start -p0 -eswe -fl -g, -head", $out_default);

        $time = strtotime("2017-3-7 0:0");
        $utdatenow = strftime("%d.%m.%Y", $time);
        $utnow = strftime("%H:%M:%S", $time);

//        echo "$utdatenow<br/>";
//        echo "$utnow<br/>";

        exec("astrolog -edirastrolog -b$utdatenow -ut$utnow -p0 -eswe -fl -g, -head", $out_default);
        $sun_deg = $out_default[0] * 1;

        $next = (floor($sun_deg / 15) + 1) * 15;

        $start += $next - floor($sun_deg) - 1;

        $time += ($next - floor($sun_deg) - 1) * 3600 * 24;
//        echo $sun_deg;
//
        echo $next . "<br/>";

//        for($i=$start;$i<$start + 1;$i += 1/60/24)
        for ($i = $time; $i < $time + 3600 * 24; $i += 60)
        {
//            exec ("astrolog -edirastrolog -bj$i -p0 -eswe -fl -g, -head", $out);

            $utdatenow_i = strftime("%d.%m.%Y", $i);
            $utnow_i = strftime("%H:%M:%S", $i);
            exec("astrolog -edirastrolog -b$utdatenow_i -ut$utnow_i -p0 -eswe -fl -g, -head", $out);

            $sun = $out[0];
//            echo $sun."<br/>";
            if ($sun >= $next - 0.0001)
            {
                echo $sun . '-' . $i . "<br/>";
                $next += 15;
                if ($next >= 360) $next = 0;
//                $ymd = jdtogregorian((int)($i));
//                $hour = ($i - (int)($i)) * 24;
//                $min = floor(($hour - floor($hour))*60);
//                echo  $ymd.' '.floor($hour).':'.$min."<br/>";
                echo date("Y-m-d H:i", $i + 8 * 3600);
                break;
            }

            unset($out);
        }
    }

    private function test2($str = '')
    {
        $str = urlencode(input('str'));
        var_dump(urlencode(input('str')));
        p($str);
//        $str = 'rXNgSeryr/43Y6ggMs9wefXLiESvlDQuSS4xr7EKAQa2yjEHFnOBkqlgmHkQnfz+GvbefD3oKAnR5+KBh+tBpCbtHaoAyLFTyAcCC7IfDf+gfm8oscei6/RI6UTyCFjRrnpDjWNxdtNPCG8pwRxXWDJYOs1TKrWYTfAFUfzQ+TIWsjK/Y+YszD4GqK4wwiNAtEsCvTUeDZErS6UMn5UtZBDnWYTVZCLOC+PTEYUigpYCKVb+MVhxCi3Txq9NxIldqWyJIsjKQRtNO9bPKF14976mQydlOKV4gt8chTPagBLu7I3DGAIMoll0lBgXy7IveVIQ3C6/il5IUCgIZhCi6Q==';

        var_dump($str);
        $private_key = openssl_pkey_get_private(config('app.private_key'));
        p(base64_decode($str));
//        p($private_key);
        openssl_private_decrypt(base64_decode(urldecode($str)), $decrypted, $private_key);

        var_dump($decrypted);
//        return ()? $decrypted : null;


//        $data = privDecrypt($str);
//
//
//
//        var_dump($data);
    }

    private function test_redis()
    {
        $redis = new Redis();
        $redis->set('test', 'hello redis');
        echo $redis->get('test');

    }

    private function redisHash()
    {
        $info_1 = AdminNode::get(1);   //对象
        $info_2 = AdminNode::get(2)->toArray();   //数组
        $info_3 = AdminNode::get(3)->toArray();   //数组
        $redis = RedisHash::instance();
        $redis->setHashKey("AdminNode:1")->set($info_1);
        $redis->setTable("AdminNode")->setKey("2")->set($info_2);
        $redis->setTable("AdminNode")->setKey("3")->set($info_3);

        //获取方式  整条数据
        echo "info_1完整数据" . PHP_EOL;
        dump($redis->setTable("AdminNode")->setKey(2)->get());
        echo "info_2完整数据" . PHP_EOL;
        dump($redis->setHashKey("AdminNode:2")->get());
        echo "info_3完整数据" . PHP_EOL;
        dump($redis->setHashKey("AdminNode:3")->get());

        //获取方式  指定字段
        echo "info_1指定字段" . PHP_EOL;
        dump($redis->setTable("AdminNode")->setKey("1")->get(["node_name", "action_name"]));
        echo "info_2指定字段" . PHP_EOL;
        dump($redis->setHashKey("AdminNode:2")->get("node_name,action_name"));
        echo "info_3指定字段" . PHP_EOL;
        dump($redis->setHashKey("AdminNode:3")->get("node_name"));

    }

    private function adb()
    {
        $all = db('user')->alias('u1')->field('u2.id')->join('app_user u2', 'u1.uc_id=u2.uc_id', 'INNER')->where('u1.id < u2.id')->select();
        if ($all || !empty($all))
        {
            foreach ($all as $k => $a)
            {
                $data = [
                    'id' => (int)($a['id']),
                    'uc_id' => md5($a['id'] . microtime())
                ];
                db('user')->where("id=" . $data['id'])->update(['uc_id' => $data['uc_id']]);
                $data = ['id' => '', 'uc_id' => ''];
            }
        }

//        foreach ($data)
        dump($all);
//        ec

//        dump($all);
    }

    // 生成24节气时间表
    private function test_astrolog()
    {
        echo "<pre>";
        $res = [];

        $start_time = isset($_GET['start_time']) ? strtotime($_GET['start_time']) : strtotime("2119-01-01 0:0:0");
        $begin = $start_time;
        $year_data = $this->get_data($start_time, 10, '1y');

        foreach ($year_data as $i1 => $yd)
        {
            $y_temp = explode(', ', $yd);
            $y_sundeg = $y_temp[1] * 1;

            $next = ceil($y_sundeg / 15) * 15;
            $y_now_start_time = $start_time;

//            echo "初始太阳度数：$y_sundeg    =====     当前循环时间".date("Y-m-d H:i:s",$y_now_start_time)."\n";

            $y_diffDeg = abs($next - floor($y_sundeg));// 太阳约一天走一度
            if ($y_diffDeg > 180) $y_diffDeg = 360 - $y_diffDeg;

            $y_diffDeg -= 2;

            $y_start_time_2day = strtotime("+{$y_diffDeg} day", $y_now_start_time);
            $deg = $next;
            $diff = 0;
            $time = $y_start_time_2day;
            for ($i = 1; $i < 25; $i++)
            {
                $day_datas = $this->get_data($time, 20, '1d');

                foreach ($day_datas as $k => $dd)
                {
                    $_temp = explode(', ', $dd)[1] * 1;

//                    echo "$k: ====  太阳度数：$_temp   ======   节令度数：$deg\n";
                    if ($deg > 15 && $_temp >= $deg)
                    {
                        $diff = $k - 1;
                        break;
                    } elseif ($deg <= 15 && floor($_temp) == $deg)
                    {
                        $diff = $k - 1;
                        break;
                    }
                }

                $time = strtotime("+{$diff} day", $time);

                $datas = $this->get_solar_terms($time, $deg);

                $res[] = [
                    'time' => $datas[0],
                    'deg' => $datas[1],
                ];

                $deg += 15;
                if ($deg >= 360) $deg = 0;

                echo "循环次数：$i   =====  {$this->get_name($datas[1])}节气时间太阳度数：{$datas[1]} ==== 实际节气时间：" . date('Y-m-d H:i:s', $datas[0]) . PHP_EOL;
            }
            $start_time = strtotime('+1 year', $start_time);// 循环时间变化
//            echo "start_time:   $start_time  \n";
        }

        $isset = Db::table('wechat_backup_07_18_14_43_00.app_solar_terms')->whereTime('time', 'between', [$begin, $start_time])->find();

        if (empty($isset) || !$isset)
        {
            Db::table('wechat_backup_07_18_14_43_00.app_solar_terms')->insertAll($res);
        } else
        {
            echo "当前数据已存在！";
            exit;
        }
    }

    private function get_name($deg = 0)
    {
        $name = '';
        switch (floor($deg))
        {
            case 0:
                $name = '春分';
                break;
            case 15:
                $name = '清明';
                break;
            case 30:
                $name = '谷雨';
                break;
            case 45:
                $name = '立夏';
                break;
            case 60:
                $name = '小满';
                break;
            case 75:
                $name = '芒种';
                break;
            case 90:
                $name = '夏至';
                break;
            case 105:
                $name = '小暑';
                break;
            case 120:
                $name = '大暑';
                break;
            case 135:
                $name = '立秋';
                break;
            case 150:
                $name = '处暑';
                break;
            case 165:
                $name = '白露';
                break;
            case 180:
                $name = '秋分';
                break;
            case 195:
                $name = '寒露';
                break;
            case 210:
                $name = '霜降';
                break;
            case 225:
                $name = '立冬';
                break;
            case 240:
                $name = '小雪';
                break;
            case 255:
                $name = '大雪';
                break;
            case 270:
                $name = '冬至';
                break;
            case 285:
                $name = '小寒';
                break;
            case 300:
                $name = '大寒';
                break;
            case 315:
                $name = '立春';
                break;
            case 330:
                $name = '雨水';
                break;
            case 345:
                $name = '惊蛰';
                break;
        }
        return $name;
    }

    /**
     * 获取节令时间
     */
    private function get_solar_terms($start = null, $next = null)
    {
        unset($day_data);
        $day_data = $this->get_data($start, 72, '60m');

        $deg = null;
//            var_dump($day_data);
        $add_h = 0;
        foreach ($day_data as $i2 => $dd)
        {
            $d_temp = explode(', ', $dd);
            $d_sundeg = $d_temp[1] * 1;

            if ($next != 0 && $d_sundeg >= $next)
            {
                $add_h = $i2;
                break;
            } elseif ($d_sundeg >= $next && $next == 0 && $d_sundeg < 300)
            {
                $add_h = $i2;
                break;
            }
            $add_h++;
        }
        $add_h--;
        $y_now_start_time = strtotime("+{$add_h} hour", $start);


        unset($minute_data);
        $minute_data = $this->get_data($y_now_start_time, 60, '1m');
//            var_dump($minute_data);
        $add_m = 0;
        foreach ($minute_data as $i3 => $md)
        {
            $m_temp = explode(', ', $md);
            $m_sundeg = sprintf("%.7f", $m_temp[1] * 1);

            if ($next != 0 && $m_sundeg >= $next)
            {
                $add_m = $i3;
                break;
            } elseif (bccomp($m_sundeg, $next) == 0 && $next == 0 && $m_sundeg < 1)
            {
                $add_m = $i3;
                break;
            }
            $add_m++;
        }
        $add_m--;
        $y_now_start_time = strtotime("+{$add_m} minute", $y_now_start_time);

        unset($second_data);
        $second_data = $this->get_data($y_now_start_time, 61, '1s');
//            var_dump($second_data);
        $add_s = 0;
        foreach ($second_data as $i4 => $sd)
        {
            $s_temp = explode(', ', $sd);
            $s_sundeg = $s_temp[1] * 1;

            if ($next != 0 && $s_sundeg >= $next)
            {
                $add_s = $i4;
                break;
            } elseif ($s_sundeg >= $next && $next == 0 && $s_sundeg < 1)
            {
                $add_s = $i4 + 10;
                break;
            }
            $add_s++;
        }
        $y_now_start_time = strtotime("+{$add_s} second", $y_now_start_time);
        $deg = sprintf("%.7f", $s_sundeg);

        return [$y_now_start_time, $deg];
    }

    /**
     *
     */
    private function get_data($time = null, $n = 0, $s = '1d')
    {
        unset($out);
        $utdatenow = strftime("%d.%m.%Y", $time);
        $utnow = strftime("%H:%M:%S", $time);
        $exec_str = "/k8s_mnt/k8s/dev/zhunle_api/astrolog/astrolog_docker -edir/k8s_mnt/k8s/dev/zhunle_api/astrolog/ -fTl -p0 -n{$n}  -b{$utdatenow} -ut{$utnow} -g, -head -s{$s}";
//        var_dump($exec_str);
        exec($exec_str, $out);
//        var_dump($out);
//        exit;
        return $out;
    }

    private function getredis()
    {
        var_dump(\think\Queue::marshal());

    }


    // public function testNotifySms()
    // {
    //     halt(\sendSms('18511696867',[],config('aliyun.dayu_rectification_code')));
    // }


    /**
     * @throws \app\common\lib\exception\ApiException
     */
    private function testAuthenticateLove()
    {
        $Recode = new Recode();
        $recode1 = $Recode->getRecode(['id' => 27]);
        $recode2 = $Recode->getRecode(['id' => 333]);

        $option = [
            'recode1' => $recode1,
            'recode2' => $recode2,
            'use_default_setting' => true,
            'get_synastry_data' => true,
        ];
        // A为底盘
        $Astrolog = Astrolog::getInstance()($option);
        $Astrolog->getAstroDatas();
        $source1 = $Astrolog->datas;
        // B为底盘
        $Astrolog->options['recode1'] = $recode2;
        $Astrolog->options['recode2'] = $recode1;
        $Astrolog->getAstroDatas();
        $source2 = $Astrolog->datas;


        $AuthenticateLove = new AuthenticateLove([
            // A为底盘 对方落我宫与我成相
            'data1' => $source1['synastry_data'][1],
            // B为底盘 对方落我宫与我成相
            'data2' => $source2['synastry_data'][1]
        ]);

        $AuthenticateLove->init();
    }


    /**
     * 测试kafka
     * @return \think\response\Json
     * @throws \RdKafka\Exception
     */
    private function testKafkaSend()
    {
        /**
         * 测试生产数据
         */
        $kafkaStatus = Kafka::getInstance()->producer('测试Kafka 生产 ' . date('YmdHis'), 'testForProducer');
        /**
         * 测试消费数据
         */
//        $kafkaStatus = Kafka::getInstance()->consumer();

        if ($kafkaStatus !== true)
        {
            return show(0, $kafkaStatus);
        } else
        {
            return show(200, '操作成功 ' . date('YmdHis'));
        }
    }

    private function testRabbitMQ()
    {
        echo "<pre>";
        // 实例化RabbitMQ封装类
        $AMQP = new AMQP;
        $msg = '普通消息：现在是北京时间：' . date('Y-m-d H:i:s');
        if ($AMQP->send($msg) === true)
        {
            echo $msg . PHP_EOL;
        } else
        {
            echo '普通消息：xxxxxx' . PHP_EOL;
        }
//        $msg = '任务消息：现在是北京时间：' . date('Y-m-d H:i:s');
//        if ($AMQP->task($msg) === true)
//        {
//            echo $msg . PHP_EOL;
//        } else
//        {
//            echo '任务消息：xxxxxx' . PHP_EOL;
//        }
//        $msg = '延时任务消息 5秒 ：现在是北京时间：' . date('Y-m-d H:i:s');
//        if ($AMQP->task($msg, 5000) === true)
//        {
//            echo $msg . PHP_EOL;
//        } else
//        {
//            echo '延时任务消息 5秒 ：xxxxxx' . PHP_EOL;
//        }
        $msg = '校准生辰：延时任务消息 1秒 ：现在是北京时间：' . date('Y-m-d H:i:s');
        if ($AMQP->task($msg, 1000, 'task.rectification') === true)
        {
            echo $msg . PHP_EOL;
        } else
        {
            echo '校准生辰：延时任务消息 1秒 ：xxxxxx' . PHP_EOL;
        }
        $msg = '运势计算：延时任务消息 2秒 ：现在是北京时间：' . date('Y-m-d H:i:s');
        if ($AMQP->task($msg, 1000, 'task.fortune') === true)
        {
            echo $msg . PHP_EOL;
        } else
        {
            echo '运势计算：延时任务消息 2秒 ：xxxxxx' . PHP_EOL;
        }
//        $msg = '延时任务消息：现在是北京时间：' . date('Y-m-d H:i:s');
//        if ($AMQP->delayTask($msg) === true)
//        {
//            echo $msg . PHP_EOL;
//        } else
//        {
//            echo '延时任务消息：xxxxxx' . PHP_EOL;
//        }
        // 关闭连接
        $AMQP->handlerClose();
    }

    /**
     *
     */
    private function testSyzygyData()
    {
//        ini_set('memory_limit','3072M');
        set_time_limit(0);
        $year = input('year/d', (int)date('Y'));
        $n = input('n/d', 1);


        $Astrolog = Astrolog::getInstance();


        $start = $Astrolog->dealTime([
            'year' => $year,
            'month' => 1,
            'day' => 1,
            'hour' => 0,
            'minute' => 0,
            'is_summer' => 0,
            'timezone' => 0,
        ]);
        echo "<pre>";

        for ($i = $start; $i < strtotime("+$n year", $start); $i = strtotime("+1 year", $start))
        {
            $data = $Astrolog->calculateSyzygyData($start, $n);

            echo "$year 年 $n 年" . PHP_EOL;
            print_r($data);
        }
    }

    /**
     * 递归去除重复准了号
     */
    private function resetRepeatUen()
    {
        $startTime = time();
        $limit = 1000;
        /**
         * 原生查询准了号重复的sql
         * select count(*) from wechat_backup_07_18_14_43_00.app_user u inner join (select uen from wechat_backup_07_18_14_43_00.app_user where uen != '' group by uen having count(uen) > 1) u2 on u.uen=u2.uen;
         */
        $sql = "select u.id from wechat_backup_07_18_14_43_00.app_user u inner join (select uen from wechat_backup_07_18_14_43_00.app_user where uen != '' group by uen having count(uen) > 1) u2 on u.uen=u2.uen where u.id!=11656297 limit {$limit}";
        $data = Db::table('wechat_backup_07_18_14_43_00.app_user')->query($sql);

        $count = count($data);

        $dataTmp = [];

        foreach ($data as $d)
        {
            $uuid = substr(md5(microtime() . $d['id'] . uniqid()), 0, 12);
            $dataTmp[] = [
                'id' => $d['id'],
                'uen' => $uuid
            ];
        }

//        halt($dataTmp);

        $UserModel = new User();

        try
        {
            $UserModel->saveAll($dataTmp);
        }
        catch (\Exception $e)
        {
            $error = $e->getMessage();
            \think\Log::error('error: ' . $error . PHP_EOL);
        }

        $endTime = time();
        $diff = $endTime - $startTime;


        $info = 'success: ' . count($data) . '个  耗时：' . $diff . 's   结束时间：' . date('Y-m-d H:i:s') . PHP_EOL;
        \think\Log::write($info, 'info', true);

        if ($count < $limit)
        {
            exit;
        }
        usleep(50);
        return $this->resetRepeatUen();
    }
}
